/*
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2019-10-22 14:30:39
 * @LastEditors: cxguo
 * @LastEditTime: 2019-10-22 17:39:29
 */
import IframeVue from './iframe'
import { parseDom, getIframeName } from '../utils/tool'
import { CONTAINER_CLASS_NAME, GLOBAL_DEFAULT_PROPERTIES } from './config'

class Iframe {
  constructor(Vue, options) {
    // [初始化]
    // 所有iframe的集合, 用obj方便直接根据名字查找iframe
    this.iframes = {}
    // iframe在最小状态的位置(设计思路 -> 添加座位.落座)
    this.minPositions = {}
    // 配置iframe的全局参数 (Vue, iframe_title_height)
    this.Vue = Vue
    this.options = options
  }
  getDefaultContainer() {
    const container = document.getElementById(CONTAINER_CLASS_NAME)
    if (container) return container
    const layerIframe = parseDom('<div id=' + CONTAINER_CLASS_NAME + '></div>')[0]
    document.body.appendChild(layerIframe)
    return document.getElementById(CONTAINER_CLASS_NAME)
  }
  /**
   * 添加iframe
   */
  add = (properties) => {
    const that = this
    const iframeName = properties.name ? properties.name : getIframeName()
    const props = Object.assign(properties, { vm: this.Vue,
      iframes: this.iframes,
      minPositions: this.minPositions,
      name: iframeName,
      options: this.options })
    const Instance = new this.Vue({
      render(h) {
        return h(IframeVue, {
          props: props
        })
      }
    })
    const component = Instance.$mount()
    const iframe = component.$children[0]
    // 组件销毁后执行操作
    iframe.$on('on-destroyed', (vm) => {
      delete that.iframes[vm.name] // 清除iframes集合中对象
    })
    // 添加节点
    const propContainer = properties.container
    const container = propContainer || this.getDefaultContainer()
    container.appendChild(iframe.$el)
    // 加入iframe集合
    this.iframes[iframeName] = iframe
    return iframe
  }

  addSingle(properties) {
    if (!properties.name) throw new Error('addSingle方法必须有name')
    const name = properties.name
    if (this.iframes[name]) return this.iframes[name]
    else return this.add(properties)
  }

  create = (properties) => {
    this.add(properties)
  }

  /**
   * 删除所有的iframe
   */
  removeAll = () => {
    this.container.innerHTML = ''
    this.minPositions = {}
  }

  /**
   * 删除单个iframe
   */
  remove = (id) => {
    return null
  }

  /**
   * 根据id获取iframe
   */
  getIframe = (id) => {
    return null
  }
}
export default Iframe
